import { fabric } from 'fabric'

export function useFilters(getCanvas) {
  const filters = {
    // 灰度
    grayscale: new fabric.Image.filters.Grayscale(),
    // 亮度
    brightness: new fabric.Image.filters.Brightness({ brightness: 0.1 }),
    // 对比度
    contrast: new fabric.Image.filters.Contrast({ contrast: 0.1 }),
    // 饱和度
    saturation: new fabric.Image.filters.Saturation({ saturation: 0.1 }),
    // 色相
    hue: new fabric.Image.filters.HueRotation({ rotation: 0 }),
    // 模糊
    blur: new fabric.Image.filters.Blur({ blur: 0.1 }),
    // 噪点
    noise: new fabric.Image.filters.Noise({ noise: 25 }),
    // 像素化
    pixelate: new fabric.Image.filters.Pixelate({ blocksize: 4 })
  }

  // 应用滤镜
  const applyFilter = (filterName, value = null) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject || !activeObject.filters) return

    const filter = filters[filterName]
    if (!filter) return

    // 更新滤镜参数
    if (value !== null) {
      switch (filterName) {
        case 'brightness':
          filter.brightness = value
          break
        case 'contrast':
          filter.contrast = value
          break
        case 'saturation':
          filter.saturation = value
          break
        case 'hue':
          filter.rotation = value
          break
        case 'blur':
          filter.blur = value
          break
        case 'noise':
          filter.noise = value
          break
        case 'pixelate':
          filter.blocksize = value
          break
      }
    }

    // 获取当前滤镜索引
    const filterIndex = activeObject.filters.findIndex(f => 
      f && f.type === filter.type
    )

    // 如果滤镜已存在，更新它；否则添加新滤镜
    if (filterIndex > -1) {
      activeObject.filters[filterIndex] = filter
    } else {
      activeObject.filters.push(filter)
    }

    // 应用滤镜
    activeObject.applyFilters()
    fabricCanvas.renderAll()
  }

  // 移除滤镜
  const removeFilter = (filterName) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject || !activeObject.filters) return

    const filter = filters[filterName]
    if (!filter) return

    // 移除指定滤镜
    activeObject.filters = activeObject.filters.filter(f => 
      f && f.type !== filter.type
    )

    // 重新应用滤镜
    activeObject.applyFilters()
    fabricCanvas.renderAll()
  }

  // 移除所有滤镜
  const removeAllFilters = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject || !activeObject.filters) return

    activeObject.filters = []
    activeObject.applyFilters()
    fabricCanvas.renderAll()
  }

  return {
    applyFilter,
    removeFilter,
    removeAllFilters
  }
} 